<template>
  <div class="">
    <header>
      <div class="close">
        <van-icon
          name="cross"
          size="30px"
          color="#fff"
          @click="$router.back()"
        />
      </div>
      <p>您好，</p>
      <p>欢迎使用铭码SCRM</p>
      <p>用户注册</p>
    </header>
    <main>
      <div class="item">
        <h3><span>*</span>公司名称</h3>
        <input type="text" placeholder="请输入公司名称" v-model="company" />
      </div>
      <div class="item">
        <h3><span>*</span>企业类型</h3>
        <van-cell title="选择行业类型" @click="show = true" is-link />
      </div>
      <div class="item">
        <h3><span>*</span>手机号</h3>
        <input type="number" placeholder="请输入您的手机号" v-model="phone" />
      </div>
      <div class="item">
        <h3><span>*</span>验证码</h3>
        <div class="code">
          <input type="number" placeholder="请输入您的验证码" v-model="code" />
          <span @click="sendCode">{{ isCode ? count : "获取验证码" }}</span>
        </div>
      </div>
      <div class="item">
        <h3><span>*</span>设置密码</h3>
        <input
          type="password"
          placeholder="请输入密码(至少8位，数字+字母)"
          v-model="password"
        />
      </div>
      <div class="item">
        <h3>输入邀请码</h3>
        <input
          type="text"
          placeholder="请输入密码(至少8位，数字+字母)"
          v-model="invite"
        />
      </div>
      <div class="item">
        <h3>
          申请期限
          <p>（付费后不分功能限制）</p>
        </h3>
        <van-radio-group
          v-model="radio"
          direction="horizontal"
          @change="changeRadio"
        >
          <van-radio :name="1" icon-size="24px">免费试用</van-radio>
          <van-radio :name="2" icon-size="24px">付费使用</van-radio>
        </van-radio-group>
        <van-radio-group
          v-model="radios"
          direction="horizontal"
          v-show="radio == 2"
          @change="changeRadio"
        >
          <van-radio :name="2" icon-size="16px" class="radios"
            >9.9元/周</van-radio
          >
          <van-radio :name="3" icon-size="16px" class="radios"
            >29.8元/月</van-radio
          >
          <van-radio :name="4" icon-size="16px" class="radios"
            >298元/年</van-radio
          >
        </van-radio-group>
        <!-- <p>免费账号试用期限为一天，选择周、月、年期限需付费开通</p> -->
      </div>
      <button @click="loginSave">立即注册</button>
      <p class="login">注册即代表同意<span>《铭码SCRM用户使用协议》</span></p>
    </main>
    <!-- 弹框 -->
    <van-action-sheet
      v-model="show"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="show = false"
      @select="select"
    />
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      radio: 2,
      radios: 2,
      company: "", //公司名称
      phone: "", //电话
      code: "", //验证码
      password: "", //密码
      invite: "", //邀请码
      count: 60, //倒计时
      timer: null,
      isCode: false,
      deadType: 1, //用户类型
      data: "",
      account: "", //新的公司ID
      h5: "",
      show: false, //弹框
      actions: [
        { name: "教育行业" },
        { name: "餐饮行业" },
        { name: "金融行业" },
        { name: "娱乐行业" },
        { name: "保险行业" },
        { name: "医疗行业" },
        { name: "服务行业" },
      ],
      isPower: 2,
      info: "",
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（访问DOM元素）
  async mounted() {
    await this.isCustomer();
    if (this.isPower == 1) {
      return this.$router.push("/mineInstructions");
    }
    if (this.isPower == 3 && this.info != " ") {
      return this.$router.push("/mineInstructions");
    }
  },
  methods: {
    //判断是否有权限创建
    async isCustomer() {
      let userWxData = JSON.parse(sessionStorage.getItem("userWxData"));
      let account = sessionStorage.getItem("agentId");
      let res = await this.$api.isCustomer({
        openId: userWxData.openid,
        account,
        id: this.$store.state.userInfo.id,
        phone: this.$store.state.userInfo.phone,
      });
      this.isPower = res.data;
      this.info = res.info;
    },
    //点击选项
    select(e) {
      this.$toast(e.name);
    },
    //选择单选框
    changeRadio(e) {
      this.deadType = e;
    },
    //点击发送验证码
    async sendCode() {
      if (this.isCode) return;
      let { phone } = this;
      if (phone.trim() == "") return this.$toast("请填写手机号！");
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!reg.test(phone)) return this.$toast("请输入合法的手机号 ！");
      let res = await this.$api.sendCode({ phone });
      if (res.code !== 0) return this.$toast(res.msg);
      // 倒计时
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.isCode = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.isCode = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    //点击注册
    async loginSave() {
      let { phone, code, password, deadType, company } = this;
      if (company.trim() == "") return this.$toast("请填写公司名称！");
      if (phone.trim() == "") return this.$toast("请填写手机号！");
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!reg.test(phone)) return this.$toast("请输入合法的手机号 ！");
      if (code.trim() == "") return this.$toast("请填写验证码！");
      if (password.trim() == "") return this.$toast("请填写密码！");

      let obj = {
        company,
        phone,
        code,
        password,
        deadType,
        userId: this.$store.state.userInfo.id,
      };
      let res = await this.$api.loginSave(obj);
      if (res.code !== 0) {
        // return this.$router.push("/loginSuccess?msg=" + 2);
        return this.$toast(res.msg);
      }
      this.account = res.account;
      this.h5 = res.data;
      if (this.radio == 2) {
        let money;
        if (this.radios == 2) {
          money = 9.9;
        } else if (this.radios == 3) {
          money = 29.8;
        } else {
          money = 298;
        }
        let obj = {
          description: "注册",
          unitPrice: money,
          openid: JSON.parse(sessionStorage.getItem("userWxData")).openid,
          type: 4,
          count: 1,
          userType: 2,
          userId: this.account,
        };
        this.$api
          .getWxConfig(obj)
          .then((response) => {
            if (response.code == 0) {
              this.data = response.data;
              this.weixinPay();
            } else {
              this.deleteAccount();
              this.$toast(response.msg);
            }
          })
          .catch((error) => {
            this.deleteAccount();
            this.$toast("请求失败", +error);
          });
      } else {
        this.$toast("注册成功！");
        setTimeout((_) => {
          window.location.replace(this.h5);
        }, 800);
      }
    },
    //解决微信内置对象报错
    weixinPay() {
      var that = this;
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            that.onBridgeReady(),
            false
          );
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", that.onBridgeReady());
          document.attachEvent("onWeixinJSBridgeReady", that.onBridgeReady());
        }
      } else {
        that.onBridgeReady();
      }
    },
    //微信内置浏览器类，weChatParameter对象中的参数是3.步骤代码中从后端获取的数据
    onBridgeReady() {
      var that = this;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          debug: true,
          appId: that.data.appId, //公众号名称，由商户传入
          timeStamp: that.data.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: that.data.nonceStr, //随机串
          package: that.data.package,
          signType: that.data.signType, //微信签名方式：
          paySign: that.data.paySign, //微信签名
          jsApiList: ["chooseWXPay"],
        },
        (res) => {
          // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            //支付成功后的操作
            that.$toast("注册成功！");
            setTimeout((_) => {
              window.location.replace(this.h5);
            }, 800);
          } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
            that.deleteAccount();
            //取消支付的操作
            that.$toast({
              message: "取消支付",
              duration: 2000,
            });
          } else {
            //支付失败的操作
            that.$toast({
              message: "支付失败",
              duration: 2000,
            });
            that.deleteAccount();
          }
        }
      );
    },
    //删除公司账号
    async deleteAccount() {
      let res = await this.$api.deleteAccount({ account: this.account });
    },
  },
};
</script>
<style scoped lang="less">
/* @import url(); 引入css类 */
header {
  width: 100%;
  height: 265px;
  background: url("../../assets/zhuce.png") no-repeat;
  background-size: 100% 100%;
  .close {
    text-align: right;
    padding: 30px 15px 0;
  }
  p {
    padding: 0 15px;
    font-size: 19px;
    font-weight: 700;
    color: #ffffff;
    line-height: 31px;
    letter-spacing: 1px;
  }
}
main {
  background-color: #ffffff;
  border-radius: 16px 16px 0px 0px;
  margin-top: -75px;
  padding: 18px 33px 33px;
  h3 {
    font-size: 16px;
    font-weight: 700;
    color: #333333;
    letter-spacing: 1px;
    margin-top: 15px;
    display: flex;
    align-items: center;
    p {
      font-size: 11px;
    }
    span {
      color: red;
    }
  }
  input {
    padding: 13px 0;
    border: none;
    font-size: 14px;
    &::placeholder {
      color: #bcbfcc;
    }
  }
  .item {
    &:nth-last-of-type(n + 2) {
      border-bottom: 1px solid #ebedf0;
    }
    .code {
      display: flex;
      align-items: center;
      justify-content: space-between;
      span {
        font-size: 14px;
        color: #5873f6;
        letter-spacing: 2px;
      }
    }
    // p {
    //   font-size: 10px;
    //   color: #5873f6;
    // }
  }
  button {
    height: 41px;
    background: linear-gradient(49deg, #7893df 5%, #4b5fe0 93%);
    border-radius: 11px;
    font-size: 14px;
    font-weight: 700;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    color: #ffffff;
    letter-spacing: 1px;
    border: none;
    margin: 40px 0 11px;
  }
  .login {
    font-size: 10px;
    color: #999999;
    text-align: center;
    span {
      color: #5873f6;
    }
  }
}
.van-radio-group--horizontal {
  margin: 15px 0;
  /deep/.van-radio__label {
    font-size: 14px;
  }
}
.radios {
  font-size: 10px;
}
</style>
